package com.gbiac.modules.monitor.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gbiac.modules.monitor.model.query.ViolationStatisticsReportQuery;
import com.gbiac.modules.monitor.service.ViolationStatisticsReportService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.DateUtils;
import org.jeecg.config.shiro.IgnoreAuth;
import org.jeecgframework.poi.excel.ExcelExportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.params.ExcelExportEntity;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * 违规统计报表
 */
@Api(tags="违规统计报表")
@RestController
@RequestMapping("/violationStatisticsReport")
@Slf4j
public class ViolationStatisticsReportController {
    @Resource
    private ViolationStatisticsReportService violationStatisticsReportService;

    @IgnoreAuth
    @ApiOperation(value="查询人员违规累计", notes="查询人员违规累计")
    @GetMapping(value = "/queryUserReport")
    public Result<Page<JSONObject>> queryUserReport(ViolationStatisticsReportQuery violationStatisticsReportQuery,
                                                    @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                                    @RequestParam(name="pageSize", defaultValue="10") Integer pageSize) {
        return Result.OK(violationStatisticsReportService.queryUserReport(violationStatisticsReportQuery,pageNo,pageSize));
    }

    @IgnoreAuth
    @ApiOperation(value="查询席位违规累计", notes="查询席位违规累计")
    @GetMapping(value = "/querySeatReport")
    public Result<Page<JSONObject>> querySeatReport(ViolationStatisticsReportQuery violationStatisticsReportQuery,
                                                    @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                                    @RequestParam(name="pageSize", defaultValue="10") Integer pageSize) {
        return Result.OK(violationStatisticsReportService.querySeatReport(violationStatisticsReportQuery,pageNo,pageSize));
    }


    /**
     * 导出excel-人员违规累计
     *
     * @param violationStatisticsReportQuery
     */
    @IgnoreAuth
//    @RequiresPermissions("monitor:gbiac_attendanceReport:exportUserReportXls")
    @RequestMapping(value = "/exportUserReportXls")
    public void exportUserReportXls(HttpServletResponse response, ViolationStatisticsReportQuery violationStatisticsReportQuery) {
        Page<JSONObject> page = violationStatisticsReportService.queryUserReport(violationStatisticsReportQuery, 1, 50000);

        List<JSONObject> records = page.getRecords();

        JSONObject head = records.get(0);

        Iterator<Map.Entry<String, Object>> iterator = head.entrySet().iterator();
        List<ExcelExportEntity> entity = new ArrayList<ExcelExportEntity>();
        entity.add(new ExcelExportEntity("姓名 \\ 日期","realname"));
        while (iterator.hasNext()){
            Map.Entry<String, Object> entry = iterator.next();
            String key = entry.getKey();
            if(key.contains("day") || key.contains("month")){
                entity.add(new ExcelExportEntity(key, key));
            }
        }
        entity.add(new ExcelExportEntity("总数","sumCount"));

        Integer queryType = violationStatisticsReportQuery.getQueryType();
        StringBuffer title = new StringBuffer(DateUtils.formatDate(violationStatisticsReportQuery.getQueryDate()));
        if(queryType == 1){
            title.append("人员违规累计");
        } else if (queryType == 2) {
            title.append("人员白班违规累计");
        }else {
            title.append("人员夜班违规累计");
        }

        List<Map<String, Object>> list = new ArrayList<>();
        for (int i=0;i<records.size();i++) {
            JSONObject json = records.get(i);
            Map<String, Object> map = new HashMap<>();
            for (ExcelExportEntity excelExportEntity : entity) {
                String key = (String) excelExportEntity.getKey();
                Object o = json.get(key);
                String replace = key.replace("day","").replace("month","");
                map.put(replace, o);
            }
            list.add(map);
        }
        HSSFWorkbook workbook = (HSSFWorkbook) ExcelExportUtil.exportExcel(new ExportParams(
                title.toString(),  title.toString()), entity, list);

        // 导出Excel
        try {
            setResponseHeader(response,title.toString());
            ServletOutputStream out = response.getOutputStream();
            workbook.write(out);
            out.flush();
            workbook.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    //发送响应流方法
    public void setResponseHeader(HttpServletResponse response, String fileName) {
        try {
            try {
                fileName = new String(fileName.getBytes(),"utf-8");
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "attachment;filename="+ fileName);
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * 导出excel-席位违规累计
     *
     * @param violationStatisticsReportQuery
     */
    @IgnoreAuth
//    @RequiresPermissions("monitor:gbiac_attendanceReport:exportSeatReportXls")
    @RequestMapping(value = "/exportSeatReportXls")
    public void exportSeatReportXls(HttpServletResponse response,ViolationStatisticsReportQuery violationStatisticsReportQuery) {
        Page<JSONObject> page = violationStatisticsReportService.querySeatReport(violationStatisticsReportQuery, 1, 50000);

        List<JSONObject> records = page.getRecords();

        JSONObject head = records.get(0);

        Iterator<Map.Entry<String, Object>> iterator = head.entrySet().iterator();
        List<ExcelExportEntity> entity = new ArrayList<ExcelExportEntity>();
        entity.add(new ExcelExportEntity("席位 \\ 日期","seatName"));
        while (iterator.hasNext()){
            Map.Entry<String, Object> entry = iterator.next();
            String key = entry.getKey();
            if(key.contains("day") || key.contains("month")){
                entity.add(new ExcelExportEntity(key, key));
            }
        }
        entity.add(new ExcelExportEntity("总数","sumCount"));

        Integer queryType = violationStatisticsReportQuery.getQueryType();
        StringBuffer title = new StringBuffer(DateUtils.formatDate(violationStatisticsReportQuery.getQueryDate()));
        if(queryType == 1){
            title.append("席位违规累计");
        } else if (queryType == 2) {
            title.append("人员席位白班违规累计");
        }else {
            title.append("人员席位夜班违规累计");
        }

        List<Map<String, Object>> list = new ArrayList<>();
        for (int i=0;i<records.size();i++) {
            JSONObject json = records.get(i);
            Map<String, Object> map = new HashMap<>();
            for (ExcelExportEntity excelExportEntity : entity) {
                String key = (String) excelExportEntity.getKey();
                Object o = json.get(key);
                String replace = key.replace("day","").replace("month","");
                map.put(replace, o);
            }
            list.add(map);
        }
        HSSFWorkbook workbook = (HSSFWorkbook) ExcelExportUtil.exportExcel(new ExportParams(
                title.toString(),  title.toString()), entity, list);

        // 导出Excel
        try {
            setResponseHeader(response,title.toString());
            ServletOutputStream out = response.getOutputStream();
            workbook.write(out);
            out.flush();
            workbook.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
